package com.workManager.controller;

import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.workManager.base.BaseController;
import com.workManager.base.BaseService;
import com.workManager.base.LoginHelper;
import com.workManager.config.RespCode;
import com.workManager.pojo.TdUser;
import com.workManager.service.RoleService;
import com.workManager.service.UserService;
import com.workManager.util.SecurityUtil;
import com.workManager.util.WebUtil;
import com.workManager.vo.CurrentUserVO;
import com.workManager.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by Thinkpad on 2017/1/12 0012.
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{



    @Autowired
    private BaseService baseService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "用户注册接口" ,notes = "用户注册接口")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Object register(HttpServletRequest request, @RequestBody TdUser user){
        ModelMap modelMap = new ModelMap();
        Assert.notNull(user.getLoginCode(),"用户账号");
        Assert.notNull(user.getPassword(),"用户密码");
        user.setCreateDate(new Date());
        user.setIsValid(true);
        user.setPassword(SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(user.getPassword())));
        userService.register(user);

        return setSuccessModelMap(modelMap);
    }


    @ApiOperation(value = "用户添加" ,notes = "用户添加")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(HttpServletRequest request, @RequestBody UserVo userVo)throws Exception{
        ModelMap modelMap = new ModelMap();
        userVo.setCreateDate(new Date());
        userVo.setIsValid(true);
        try{
            userService.add(userVo);
        }catch (DuplicateKeyException e){
            return setModelMap(modelMap, RespCode.INTERNAL_SERVER_ERROR, "员工名称或帐号重复");
        }
        return  setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "用户更新" ,notes = "用户更新")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(@RequestBody UserVo userVo)throws Exception{
        ModelMap modelMap = new ModelMap();
        TdUser oldUser = userService.queryUserByLoginCode(userVo.getLoginCode());
        userVo.setPassword(oldUser.getPassword());
        userVo.setIsValid(true);

        try {
            userService.update(userVo);
        }catch (DuplicateKeyException e){
            return setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"用户名："+userVo.getUserName()+"已存在,请更换！");
        }

        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "个人资料修改" ,notes = "个人资料修改")
    @RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
    public Object updateUserInfo(@RequestParam(value="userName", required = false) String userName,
                                 @RequestParam(value="loginCode", required = false) String loginCode,
                                 @RequestParam(value="email", required = false) String email,
                                 @RequestParam(value="mobile", required = false) String mobile) throws Exception {
        ModelMap modelMap = new ModelMap();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userName",userName);
        map.put("loginCode",loginCode);
        map.put("email",email);
        map.put("mobile",mobile);
        try {
            userService.updateUserInfo(map);
        }catch (DuplicateKeyException e){
            return setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"用户名："+userName+" 或登录账号："+loginCode+"已存在！");
        }

        return  setSuccessModelMap(modelMap);
    }

    @ApiOperation(value = "用户查询接口" ,notes = "用户查询接口,根据组织Id查")
    @RequestMapping(value = "/queryByOraganizationId",method = RequestMethod.POST)
    public Object queryByOraganizationId(HttpServletRequest request,@RequestParam(value = "pageNumber",required = false) String pageNumber,
                                             @RequestParam(value="pageSize", required = false) String pageSize,
                                             @RequestParam(value="organizationId", required = false) String organizationId
                                        ){

      //  Assert.notNull(organizationId,"组织Id");
        ModelMap modelMap = new ModelMap();
        Integer pagenum = pageNumber==null?1:Integer.parseInt(pageNumber);
        Integer pagesize = pageSize==null?10:Integer.parseInt(pageSize);
        Map<String,Object> dataMap = new HashMap<String, Object>();
        Map<String,Object> map = new HashMap();
        map.put("pagenum",pagenum);
        map.put("pagesize",pagesize);
        map.put("organizationId",organizationId);


        PageInfo<TdUser> userPageInfo = userService.queryByOraganizationId(map);
        dataMap.put("total",userPageInfo.getTotal());
        dataMap.put("rows",userPageInfo.getList());
        return setSuccessModelMap(modelMap,dataMap);
    }

    @ApiOperation(value = "用户查询接口" ,notes = "用户查询接口")
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public Object query(@RequestParam(value = "pageNumber",required = false) String pageNumber,
                        @RequestParam(value="pageSize", required = false) String pageSize,
                        @RequestParam(value="userName", required = false) String userName,
                        @RequestParam(value="loginCode", required = false) String loginCode,
                        @RequestParam(value="organizationId", required = false) String organizationId,
                        @RequestParam(value="roleId", required = false) String roleId)throws Exception{

        ModelMap modelMap = new ModelMap();
        Integer pagenum = pageNumber==null?1:Integer.parseInt(pageNumber);
        Integer pagesize = pageSize==null?10:Integer.parseInt(pageSize);

        Map<String,Object> map = new HashMap();
        map.put("pagenum",pagenum);
        map.put("pagesize",pagesize);
        map.put("loginCode",loginCode);
        map.put("userName",userName);
        map.put("organizationId",organizationId);
        map.put("roleId",roleId);
        Map<String,Object> dataMap = userService.query(map);
        return setSuccessModelMap(modelMap,dataMap);
    }

    @ApiOperation(value="密码修改接口",notes="密码修改接口")
    @RequestMapping(value = "passwordModify",method = RequestMethod.POST)
    public Object passwordModify(@RequestParam String loginCode,@RequestParam String oldPassword,@RequestParam String newPassword){
        ModelMap modelMap = new ModelMap();
        Assert.notNull(loginCode,"登陆账号");
        Assert.notNull(newPassword,"新密码");
        Assert.notNull(oldPassword,"旧密码");

        TdUser user = userService.queryUserByLoginCode(loginCode);
        if(user!=null && SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(oldPassword)).equals(user.getPassword())){
            String passWord = SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(newPassword));
            userService.passwordModify(loginCode,passWord);
        }else {
            return setModelMap(modelMap, RespCode.OLDPASSWORD_NULL);
        }


        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value="密码重置接口",notes="密码重置接口")
    @RequestMapping(value = "resetPassword",method = RequestMethod.POST)
    public Object resetPassword(@RequestParam String loginCode){
        ModelMap modelMap = new ModelMap();
        Assert.notNull(loginCode,"登陆账号");

        TdUser user = userService.queryUserByLoginCode(loginCode);
        if(user!=null){
            //重置密码为123456
            userService.passwordModify(loginCode,SecurityUtil.encryptMd5(SecurityUtil.encryptSHA("123456")));
        }else {
            return setModelMap(modelMap, RespCode.USER_INVALID);
        }


        return setSuccessModelMap(modelMap);
    }

 /*   public Object validatePassword(HttpServletRequest request,@RequestParam String loginCode,@RequestParam String password){
        ModelMap modelMap = new ModelMap();
        Assert.notNull(loginCode,"登陆账号");
        Assert.notNull(password,"新密码");


        String passWord = SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(password));
        TdUser tdUser = userService.queryUserByLoginCode(loginCode);
        if(passWord.equals(tdUser))
    }*/

    @ApiOperation(value="用户登录接口",notes="用户登录接口")
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public Object login(@RequestParam String loginCode,@RequestParam String password){
        loginCode = loginCode.trim();
        password = password.trim();
        ModelMap modelMap = new ModelMap();
        Assert.notNull(loginCode,"登陆账号");
        Assert.notNull(password,"登陆密码");
        String msg = "成功登录";
        try{
            if(LoginHelper.login(loginCode, SecurityUtil.encryptMd5(SecurityUtil.encryptSHA(password)))){
                return  setSuccessModelMap(modelMap);
            }
        }catch (Exception e){
            e.printStackTrace();
            msg = e.getMessage();
        }

        return  setModelMap(modelMap, RespCode.ACCOUNT_PASSWORD_ERROR, msg);
    }

    /**
     *
     * @Title: unauthorized
     * @Description: 没有登录
     * @param @param modelMap
     * @param @return
     * @return Object
     * @author linz
     * @throws
     */
    @ApiOperation(value = "没有登录")
    @RequestMapping(value="/unauthorized",method = RequestMethod.GET)
    public Object unauthorized(ModelMap modelMap) {
//		SecurityUtils.getSubject().logout();
        return setModelMap(modelMap, RespCode.UNAUTHORIZED);
    }
    /**
     *
     * @Title: forbidden
     * @Description: 没有权限
     * @param @param modelMap
     * @param @return
     * @return Object
     * @author linz
     * @throws
     */
    @ApiOperation(value = "没有权限")
    @RequestMapping(value="/forbidden",method = RequestMethod.GET)
    public Object forbidden(ModelMap modelMap) {
        return setModelMap(modelMap, RespCode.FORBIDDEN);
    }

    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Object delete(ModelMap modelMap,
                             @ApiParam(required = true, value = "用户id集合，多个用逗号分隔") @RequestParam(value = "userIds", required = false) Integer[] userIds) {
        Assert.notNull(userIds, "用户id");
        Map<String,Object> reltMap = null;
        try {
            reltMap= userService.delete(userIds);
        }catch (DataIntegrityViolationException e){
            return  setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"请先确认该员工没有负责的项目");
        }
        return setSuccessModelMap(modelMap, reltMap);
    }

    /**
     *
     * @Title: logout
     * @Description: 用户登出
     * @param @param modelMap
     * @param @return
     * @return Object
     * @author linzh
     * @throws
     */
    @ApiOperation(value = "用户登出")
    @RequestMapping(value="/logout",method = RequestMethod.GET)
    public Object logout(ModelMap modelMap) {
        SecurityUtils.getSubject().logout();
        return setSuccessModelMap(modelMap);
    }

    /**
     * 获取用户权限编码列表
     * @return Object
     * @author linzh
     * @param modelMap
     */
    @ApiOperation(value = "获取用户权限编码列表")
    @RequestMapping(value="/getRoleFuncCodeByUser",method = RequestMethod.GET)
    public Object getRoleFuncCodeByUser(ModelMap modelMap) {
        CurrentUserVO userVO = WebUtil.getCurrentUserVO();
        List list = new ArrayList();
        if (userVO != null) {
            list = roleService.getRoleFunctionCodeByUserId(userVO.getUid());
        }

        return setSuccessModelMap(modelMap,list);
    }
}
